package com.app.web.user.app;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.app.utils.base.j2se.Common;
import com.app.utils.base.j2se.Logger;
import com.app.utils.redis.Redis;
import com.app.web.user.login.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * APP信息管理器 管理平台的app信息
 * 定时从数据库加载app信息到内存中
 */
//@Service
public class AppInfoManager implements Runnable{

	@Autowired
	private LoginService loginModel;
	@Autowired
	private AppInfoService appInfoModel;
	
	private static Map<String, AppInfo> apps = new HashMap<>();
	
	/**
	 * 通过应用Key获取应用信息
	 * 应用Key就是数据库的app_id 和 app 的 id 不一样
	 * @param appKey 应用Key
	 * @return 应用信息
	 */
	public static AppInfo get(String appKey){
		return apps.get(appKey);
	}
	
	@PostConstruct
	public void init(){
		load();
		accessToken();
		new Thread(this).start();
	}
	
	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(60000);
				load();
				accessToken();
			} catch (Exception e) {}
		}
	}

	public WxMaService wxMaService(AppInfo appInfo) {
		WxMaService service = new WxMaServiceImpl();
		WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
		config.setAppid(appInfo.getApp_id());
		config.setSecret(appInfo.getSecret());
		config.setToken(appInfo.getToken());
		config.setAesKey(appInfo.getKey());
		config.setMsgDataFormat(appInfo.getFormat());
		service.setWxMaConfig(config);
		return service;
	}
	
	private void accessToken(){
		for(AppInfo appInfo : apps.values()){
			if(Common.isEmpty(appInfo.getApp_id()) || Common.isEmpty(appInfo.getSecret()) || !appInfo.getApp_id().startsWith("wx") || Common.isEmpty(Redis.key)){
				continue;
			}
			if(loginModel.accessTokenTime(appInfo) <= 300){
				try {
					loginModel.accessTokenRefresh(appInfo);
					Logger.info("成功刷新微信accessToken "+appInfo.getName()+" "+appInfo.getApp_id());
				} catch (Exception e) {
					Logger.error("accessTokenRefresh", e);
				}
			}
		}
	}

	private void load(){
		try {
			List<AppInfo> list = appInfoModel.list();
			if(Common.isEmpty(list)){
				return;
			}
			for(AppInfo app : list){
				app.setWxMaService(wxMaService(app));
				apps.put(app.getApp_id(), app);
			}
		} catch (Exception e) {
			Logger.error("加载app列表", e);
		}
	}
	
}
